package study.javaee.practice.service.impl;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import study.javaee.practice.property.SecurityProperty;
import study.javaee.practice.service.SymEncService;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;

@Component
public class SymEncServiceImpl implements SymEncService {

    @Autowired
    SecurityProperty securityProperty;

    @Override
    public String decryptToStr(String b64EncData, SymmetricCrypto crypto) {
        return crypto.decryptStr(b64EncData);
    }

    @Override
    public String decryptToStr(String strForm, byte[] key) {
        return decryptToStr(strForm, new AES(Mode.CBC,Padding.ZeroPadding, key));
    }

    @Override
    public String decryptToStr(String b64EncData, SecretKey key) {
        return decryptToStr(b64EncData, key.getEncoded());
    }

    @Override
    public String encryptToStr(String data, SymmetricCrypto crypto) {
        return crypto.encryptBase64(data);
    }

    @Override
    public String encryptToStr(String jsonData, SecretKey key) {
        return encryptToStr(jsonData, new AES(Mode.CBC,Padding.ZeroPadding, key));
    }

    @Override
    public SecretKey generateSecretKey(String sKey) {
        return (new AES(Mode.CBC,Padding.ZeroPadding, sKey.getBytes())).getSecretKey();
    }

    @Override
    public SymmetricCrypto generateCrypto(String sKey, String iv) {
        return new AES(Mode.CBC,Padding.ZeroPadding, sKey.getBytes(),
                StringUtil.isNullOrEmpty(iv)?null: iv.getBytes());
    }

    @Override
    public SymmetricCrypto generateCrypto(String sKey) {
        return  generateCrypto(sKey, null);
    }

    @Override
    public SymmetricCrypto setCrypto(String key, String iv, HttpServletRequest request) {
        SymmetricCrypto crypto = generateCrypto(key, iv);
        request.getSession().setAttribute(securityProperty.getSymKeyAttrName(), crypto);
        return crypto;
    }

    @Override
    public SymmetricCrypto getCrypto(HttpServletRequest request) {
        return (SymmetricCrypto)request.getSession().getAttribute(securityProperty.getSymKeyAttrName());
    }

    @Override
    public SecretKey generateSecretKey(String sKey, String iv) {
        SymmetricCrypto aes = new AES(Mode.CBC,Padding.ZeroPadding, sKey.getBytes(),
                StringUtil.isNullOrEmpty(iv)?null: iv.getBytes());
        return aes.getSecretKey();
    }

    @Override
    public String getEncType() {
        return SymmetricAlgorithm.AES.getValue();
    }
}
